//
//  ExamineViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/23.
//

#import "ExamineViewController.h"
#import "ExamineModel.h"
#import "joinScreenModel.h"
#import "TimeFrameShowView.h"
#import "ExamineTableViewCell.h"
#import "ExamineDetailsViewController.h"
#import "ExamineScreenViewController.h"
#import "ExamineResultViewController.h"

@interface ExamineViewController ()

@property (nonatomic ,strong)  UIView * btnline;

@property (nonatomic ,strong) UIButton * SXBtn;

@property (nonatomic ,strong) NSMutableArray <ExamineModel *> * modelArray;

@property (nonatomic ,strong) joinScreenModel * model;

@property (nonatomic ,strong) NSMutableArray <redBtn *> * btnArray;
///获取数量
@property (nonatomic ,strong) NSURLSessionDataTask * task;


@end

@implementation ExamineViewController

- (NSMutableArray<redBtn *> *)btnArray{
    if(!_btnArray){
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}
-(NSMutableArray<ExamineModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (joinScreenModel *)model{
    if(!_model){
        _model = [joinScreenModel new];
        _model.createTime = [NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM"];
    }
    return _model;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.btnArray.count > 0){

        if(self.model.status == 0){
            [self btnclickWithTitle:@"全部"];
        } else if(self.model.status == 1){
            [self btnclickWithTitle:@"待审批"];
        } else if(self.model.status == 2){
            [self btnclickWithTitle:@"已同意"];
        } else if(self.model.status == 3){
            [self btnclickWithTitle:@"已拒绝"];
        } else if(self.model.status == 4){
            [self btnclickWithTitle:@"已撤销"];
        }
    }
       
    self.SXBtn.selected = ((self.model.applyType > 0) || self.model.startTime.length > 0);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.shutDownBack = YES;
    self.isTableviewZD = YES;
    self.view.backgroundColor = KcolorHex(@"#FBFBFB");
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    
  
    
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(120));
    }];
    
    
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    
    
    UILabel * leftlab = [DTKTool labelWithText:@"审核记录" andFont:kCFont(19) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(43));
        make.centerY.offset(0);
    }];
    
    UIView * ssview = [UIView new];
    ssview.backgroundColor = KcolorHex(@"#F1F5FA");
    [self.view addSubview:ssview];
    [ssview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.height.offset(kwt(48));
        make.top.equalTo(topview.mas_bottom);
    }];
    UIButton * jjSSBtn = [UIButton buttonWithType:0];
    jjSSBtn.addimg([UIImage imageNamed:@"seach"]).addTarget(self,@selector(jjssBtnclick));
    [topview addSubview:jjSSBtn];
    [jjSSBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-15));
        make.centerY.equalTo(leftlab);
        make.width.height.offset(kwt(30));
    }];
 
    
    UIScrollView * scrollview = [UIScrollView new];
    scrollview.showsVerticalScrollIndicator  = NO;
    scrollview.showsHorizontalScrollIndicator  = NO;
//    scrollview.scrollEnabled = NO;
    [ssview addSubview:scrollview];
    scrollview.frame = CGRectMake(0, 0, SCREEN_WIDTH - kwt(80), kwt(48));
//    scrollview.pagingEnabled = YES;
    
    ///处理状态 1 待审核 2 已同意 3 已拒绝 4 已撤销
    CGFloat X = 0;
    CGFloat BtnW = kwt(70);
    for (NSString * str in @[@"全部",@"待审批",@"已同意",@"已拒绝",@"已撤销"]) {
        redBtn * btn = [redBtn NewView];
        btn.title = str;
        btn.count = 0;
        btn.openBlock = ^(NSString * _Nonnull title) {
            [weakSelf btnclickWithTitle:title];
        };
        [scrollview addSubview:btn];
        btn.frame = CGRectMake(X, 0, BtnW, kwt(48));
        X += BtnW;
        [self.btnArray addObject:btn];
    }
    scrollview.contentSize = CGSizeMake(X, 0);
    UIView * btnline = [UIView new];
    self.btnline = btnline;
    [DTKTool YJ:kwt(1.5) andView:btnline];
    btnline.backgroundColor = [UIColor gradientColorWithSize:CGSizeMake(kwt(26), 1) direction:GradientColorDirectionLevel startColor:KcolorHex(@"#4965FE") endColor:KcolorHex(@"#1983FA")] ;
    [scrollview addSubview:btnline];
    [self btnclickWithTitle:@"全部"];
    
    
  
    
    
    UIButton * SXBtn = [UIButton buttonWithType:0];
    self.SXBtn = SXBtn;
    SXBtn.addTarget(self,@selector(SXBtnClick));
    SXBtn.addNormalText(@"筛选").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17));
    [SXBtn setTitleColor:KcolorHex(@"#0967FF") forState:UIControlStateSelected];
    [SXBtn setImage:[UIImage imageNamed:@"CRscreen"] forState:UIControlStateNormal];
    [SXBtn setImage:[UIImage imageNamed:@"CRscreen2"] forState:UIControlStateSelected];
    [SXBtn setImageEdgeInsets:UIEdgeInsetsMake(0, kwt(50), 0, 0)];
    [SXBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, kwt(-40), 0, 0)];
    [ssview addSubview:SXBtn];
    [SXBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.top.offset(0);
        make.width.offset(kwt(80));
    }];
    UIView * ssline = [UIView new];
    ssline.backgroundColor = KcolorHex(@"#C4C4C4");
    [ssview addSubview:ssline];
    [ssline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.offset(0);
        make.width.offset(0.5);
        make.height.offset(kwt(14));
    }];
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#EBEDF0");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(ssview.mas_bottom);
    }];
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
    [self addHeaderView:^{
        [weakSelf refreshingData];
    }];
}
- (void)jjssBtnclick{
    ExamineResultViewController * vc = [ExamineResultViewController new];
    joinScreenModel * model = [joinScreenModel new];
    model.createTime = [NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM"];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)btnclickWithTitle:(NSString *)title{
    for (redBtn * btn in self.btnArray) {
        if([btn.title isEqualToString:title]){
            ///1 待审批 2 已同意 3 已拒绝 4 已撤销
            if([btn.title isEqualToString:@"已同意"]){
                self.model.status = 2;
                [UIView animateWithDuration:0.25 animations:^{
                    self.btnline.frame = CGRectMake(kwt(22 + 70 * 2), kwt(45), kwt(26), kwt(3));
                }];
            } else  if([btn.title isEqualToString:@"待审批"]){
                self.model.status = 1;
                [UIView animateWithDuration:0.25 animations:^{
                    self.btnline.frame = CGRectMake(kwt(22 + 70), kwt(45), kwt(26), kwt(3));
                }];
            } else  if([btn.title isEqualToString:@"已拒绝"]){
                self.model.status = 3;
                [UIView animateWithDuration:0.25 animations:^{
                    self.btnline.frame = CGRectMake(kwt(22 + 70 * 3), kwt(45), kwt(26), kwt(3));
                }];
            } else  if([btn.title isEqualToString:@"已撤销"]){
                self.model.status = 4;
                [UIView animateWithDuration:0.25 animations:^{
                    self.btnline.frame = CGRectMake(kwt(22 + 70 * 4), kwt(45), kwt(26), kwt(3));
                }];
            } else {
                self.model.status = 0;
                [UIView animateWithDuration:0.25 animations:^{
                    self.btnline.frame = CGRectMake(kwt(22), kwt(45), kwt(26), kwt(3));
                }];
            }
            btn.isSeled = YES;
        } else {
            btn.isSeled = NO;
        }
       
        
    }
    [self refreshingData];
}
- (void)openSPSL{
  
    NSMutableDictionary * dict = [self.model SHDict];
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    
   [SCNetManger PostAuditGetAuditCountModelWithDict:dict andCompetionHandlerBlock:^(HTTPArrBase * model) {
//        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray<AuditCountModel *> * array = [NSArray yy_modelArrayWithClass:AuditCountModel.class json:model.result];
            for (redBtn * btn in self.btnArray) {
                for (AuditCountModel * countModel in array) {
                    if([btn.title isEqualToString:countModel.statusName]){
                        btn.count = countModel.count;
                    }
                }
            }
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];

}


- (void)SXBtnClick{
    ExamineScreenViewController * vc = [ExamineScreenViewController new];
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)loadNewData {
    [self openSPSL];
    if(self.task){
        [self.task cancel];
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [self.model SHDict];
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    
    self.task = [SCNetManger PostAuditGetAppAuditListWithDict:dict andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        self.task = nil;
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:ExamineModel.class json:model.result];
            [self.modelArray addObjectsFromArray:array];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer endRefreshing];
            }
            [self.tableview.mj_header endRefreshing];
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}


//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return kwt(100);
//}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerview = [UIView new];
    headerview.backgroundColor = KcolorHex(@"#EBEDF0");
    UIView * btnview = [UIView new];
    MJWeakSelf
    btnview.addClickBlock(^{
        [weakSelf openTime];
    });
    [headerview addSubview:btnview];
    btnview.backgroundColor= UIColor.whiteColor;
    [DTKTool YJ:kwt(4) andView:btnview];
    [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(10));
        make.height.offset(kwt(31));
    }];
    UILabel * time = [DTKTool labelWithText:@"-" andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
    [btnview addSubview:time];
    [time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(11));
    }];
    
    UIImageView * img = kimageView(@"arrow_down");
    [btnview addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-11));
        make.width.offset(kwt(12));
        make.height.offset(kwt(7));
        make.left.equalTo(time.mas_right).offset(kwt(11));
    }];
    if(self.model.startTime.length > 0){
        if([self.model.startTime isEqualToString:self.model.endTime]){
            time.text = self.model.startTime;
        } else {
            time.text = [NSString stringWithFormat:@"%@~%@",self.model.startTime,self.model.endTime];
        }
    } else {
        time.text = self.model.createTime;
    }
    return headerview;
    
}


- (void)openTime{
    MJWeakSelf
    if(self.model.startTime.length > 0){
        [TimeFrameShowView showviewWithTitle:@"请选择任务时间" andStartTime:self.model.startTime andEndTime:self.model.endTime andRightBlock:^(NSString * _Nonnull StartTime, NSString * _Nonnull EndTime) {
            weakSelf.model.endTime = EndTime;
            weakSelf.model.startTime = StartTime;
            [weakSelf refreshingData];
        } andCZBlock:^{
            weakSelf.model.endTime = @"";
            weakSelf.model.startTime = @"";
            weakSelf.SXBtn.selected = ((weakSelf.model.applyType > 0) || weakSelf.model.startTime.length > 0);
            [weakSelf refreshingData];
        }];
    } else{
        
        [BRDatePickerView showDatePickerWithMode:BRDatePickerModeYM title:@"请选择任务申请时间" selectValue:self.model.createTime minDate:nil maxDate:nil isAutoSelect:NO resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
            weakSelf.model.createTime = selectValue;
            [weakSelf refreshingData];
        }];
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kwt(50);
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.modelArray[indexPath.row].cellH;
//    return kwt(200);
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    
    ExamineTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ExamineTableViewCell"];
    if (cell == nil) {
        cell = [[ExamineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ExamineTableViewCell"];
    }
    if(self.modelArray.count > indexPath.row){
        cell.model = self.modelArray[indexPath.row];

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell ;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ExamineDetailsViewController * vc = [ExamineDetailsViewController new];
    vc.auditId = self.modelArray[indexPath.row].ID;
    [self.navigationController pushViewController:vc animated:YES];
}
@end

@interface redBtn()

@property (nonatomic ,strong) UILabel * lab;
@property (nonatomic ,strong) UILabel * redlab;

@end
@implementation redBtn

+ (instancetype)NewView{
    redBtn * view = [redBtn new];
    [view setupview];
    return view;
}
- (void)setupview{
    UILabel * lab = [DTKTool labelWithText:@"-" andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
    [self addSubview:lab];
    self.lab = lab;
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    UILabel * redlab = [DTKTool labelWithText:@"0" andFont:kCFont(10) andTextColor:UIColor.whiteColor];
    redlab.backgroundColor = KcolorHex(@"#FE5402");
    redlab.hidden = YES;
    redlab.textAlignment = NSTextAlignmentCenter;
    [DTKTool YJ:kwt(8) andView:redlab];
    [self addSubview:redlab];
    self.redlab = redlab;
    [redlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.top.offset(kwt(5));
        make.width.height.offset(kwt(16));
    }];
    MJWeakSelf
    self.addClickBlock(^{
        [weakSelf openClick];
    });
}
- (void)openClick{
    if(self.openBlock){
        self.openBlock(self.title);
    }
}

- (void)setTitle:(NSString *)title{
    _title = title;
    self.lab.text = title;
}
- (void)setCount:(int)count{
    if(count > 0){
        self.redlab.text = [NSString stringWithFormat:@"%d",count];
        self.redlab.hidden = NO;
    } else {
        self.redlab.hidden = YES;
    }
}
-(void)setIsSeled:(BOOL)isSeled{
    _isSeled = isSeled;
    if(isSeled){
        self.lab.font = kCFont(20);

    } else {
        self.lab.font = kFont(16);

    }
}
@end
